import institution from '@/mock/data/institution';
var Fly = require("flyio/dist/npm/wx");
var fly = new Fly;
//定义公共headers
fly.config.headers = {
	'content-type': 'application/x-www-form-urlencoded'
}
//设置超时
fly.config.timeout = 10000;
fly.interceptors.request.use((request) => {
	if (!uni.getStorageSync('token')) { //检查本地缓存是否有token存在没有则重新获取
		request.headers = { //设置请求头
			"content-type": "application/json",
			"cld.stats.page_entry": uni.getStorageSync('scene'),
			"version": '1',
			"token": uni.getStorageSync('token')
		}
		let tag=request.url.split('/')[2];
		if(tag){
			let data=institution[tag](request.body);
			return Promise.resolve(data);
		}
		
		return request;
	} else {
		fly.lock(); //锁住请求
		return app.Load().then(res => { //重新获取token
			request.timeout = 30000,
				request.headers = { //设置请求头
					"content-type": "application/json",
					"cld.stats.page_entry": uni.getStorageSync('scene'),
					"version": '1',
					"token": uni.getStorageSync('token')
				}
			uni.showLoading({
				title: "加载中",
				mask: true,
			});
			fly.unlock(); //解锁请求
			return request; //继续之前的请求
		})
	}
})

// fly.interceptors.response.use(
// 	(response) => {
// 		console.log(response)
// 		uni.hideLoading();
// 		return response; //请求成功之后将返回值返回
// 	},
// 	(err) => {
// 		//请求出错，根据返回状态码判断出错原因
// 		console.log(err)
// 		uni.hideLoading();
// 		if (err.status == 0) {
// 			return "网络连接异常"
// 		} else if (err.status == 1) {
// 			return "网络连接超时"
// 		} else if (err.status == 401) {
// 			return "用户未登录"
// 		} else {
// 			if (err.response.data.message) {
// 				return err.response.data.message
// 			} else {
// 				return '请求数据失败,请稍后再试'
// 			}
// 		};
// 		// Do something with response error
// 	}
// )
// 添加响应拦截器
fly.interceptors.response.use((res) => {
	uni.hideLoading();
	if (!res.data) {
		return Promise.reject(res)
	}
	return res
}, (error) => {
	uni.hideLoading();
	return Promise.reject(error)
})
export default {
	fly: fly
}
